<%#
 Copyright 2013-2018 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd
                        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <property name="now" value="now()" dbms="h2"/>

    <%_ if (prodDatabaseType === 'mysql' || prodDatabaseType === 'mariadb') { _%>
    <property name="now" value="now()" dbms="mysql"/>
    <property name="autoIncrement" value="true"/>
    <%_ } _%>
    <%_ if (prodDatabaseType === 'postgresql') { _%>
    <property name="now" value="current_timestamp" dbms="postgresql"/>
    <%_ } _%>
    <%_ if (prodDatabaseType === 'oracle') { _%>
    <property name="now" value="sysdate" dbms="oracle"/>
    <%_ } _%>
    <%_ if (prodDatabaseType === 'mssql') { _%>
    <property name="now" value="GETDATE()" dbms="mssql"/>
    <%_ } _%>

    <property name="floatType" value="float4" dbms="postgresql, h2"/>
    <property name="floatType" value="float" dbms="mysql, oracle, mssql"/>

    <!--
        Added the entity <%= entityClass %>.
    -->
    <changeSet id="<%= changelogDate %>-1" author="jhipster">
        <%_ if (typeof javadoc == 'undefined') { _%>
        <createTable tableName="<%= entityTableName %>">
        <%_ } else { _%>
        <createTable tableName="<%= entityTableName %>" remarks="<%- formatAsLiquibaseRemarks(javadoc) %>">
        <%_ } _%>
            <column name="id" type="bigint" autoIncrement="${autoIncrement}">
                <constraints primaryKey="true" nullable="false"/>
            </column><% for (idx in fields) {
            let nullable = true;
            if (fields[idx].fieldValidate === true && fields[idx].fieldValidateRules.includes('required')) {
                nullable = false;
            }
            let unique = false;
            if (fields[idx].fieldValidate === true && fields[idx].fieldValidateRules.includes('unique')) {
                unique = true;
            }
            let maxlength = 255;
            if (fields[idx].fieldValidate === true && fields[idx].fieldValidateRules.includes('maxlength')) {
                maxlength = fields[idx].fieldValidateRulesMaxlength;
            }
            const fieldType = fields[idx].fieldType;
            const fieldTypeBlobContent = fields[idx].fieldTypeBlobContent;
            const columnName = fields[idx].fieldNameAsDatabaseColumn;
            let columnType;
            if (fieldType === 'String' || fields[idx].fieldIsEnum) {
                columnType="varchar(" + maxlength + ")";
            } else if (fieldType === 'Integer') {
                columnType="integer";
            } else if (fieldType === 'Long') {
                columnType="bigint";
            } else if (fieldType === 'Float') {
                columnType="${floatType}";
            } else if (fieldType === 'Double') {
                columnType="double";
            } else if (fieldType === 'BigDecimal') {
                columnType="decimal(10,2)";
            } else if (fieldType === 'LocalDate') {
                columnType="date";
            } else if (fieldType === 'Instant') {
                columnType="datetime";
            } else if (fieldType === 'ZonedDateTime') {
                columnType="datetime";
            } else if (fieldType === 'byte[]' && fieldTypeBlobContent !== 'text') {
                if (prodDatabaseType === 'mysql' || prodDatabaseType === 'postgresql' || prodDatabaseType === 'mariadb') {
                    columnType="longblob";
                } else {
                    columnType="blob";
                }
            } else if (fieldTypeBlobContent === 'text') {
                columnType="clob";
            } else if (fieldType === 'Boolean') {
                if (prodDatabaseType === 'postgresql') {
                    columnType="boolean";
                } else {
                    columnType="bit";
                }
            }
            %>
            <%_ if (typeof fields[idx].javadoc == 'undefined') { _%>
            <column name="<%=columnName %>" type="<%=columnType %>">
            <%_ } else { _%>
            <column name="<%=columnName %>" type="<%=columnType %>" remarks="<%- formatAsLiquibaseRemarks(fields[idx].javadoc) %>">
            <%_ } _%>
                <%_ if (unique) { 
                    const uniqueConstraintName = getUXConstraintName(entityTableName, columnName, prodDatabaseType);
                _%>
                <constraints nullable="<%= nullable %>" unique="true" uniqueConstraintName="<%= uniqueConstraintName %>" />
                <%_ } else { _%>
                <constraints nullable="<%= nullable %>" />
                <%_ } _%>
            </column>
            <%_ if (fieldType === 'byte[]' && fieldTypeBlobContent !== 'text') { _%>
            <column name="<%=columnName %>_content_type" type="varchar(255)">
                <constraints nullable="<%= nullable %>" />
            </column>
            <%_ }  _%>
            <%_ } _%><% for (idx in relationships) {
                let nullable_relation = true,
                relationshipType = relationships[idx].relationshipType,
                relationshipName = relationships[idx].relationshipName;
                if (relationships[idx].relationshipValidate === true && relationships[idx].relationshipRequired) {
                    nullable_relation = false;
                }
                if (relationships[idx].relationshipType === 'many-to-one') { %>
            <column name="<%=getColumnName(relationshipName) %>_id" type="<%_ if (relationshipName === 'user' && authenticationType === 'oauth2') { _%>varchar(100)<%_ } else { _%>bigint<%_ } _%>">
                <constraints nullable="<%= nullable_relation %>" />
            </column>
            <%_ } else if (relationshipType === 'one-to-one' && relationships[idx].ownerSide === true) { 
                const uniqueConstraintName = getUXConstraintName(entityTableName, getColumnName(relationshipName) + '_id', prodDatabaseType);
            _%>
            <column name="<%=getColumnName(relationshipName) %>_id" type="bigint">
                <constraints unique="true" nullable="<%= nullable_relation %>" uniqueConstraintName="<%= uniqueConstraintName %>" />
            </column><% } %><% } %>
            <!-- jhipster-needle-liquibase-add-column - JHipster will add columns here, do not remove-->
        </createTable>
        <%_ for (const idx in fields) {
            if (fields[idx].fieldType === 'ZonedDateTime' || fields[idx].fieldType === 'Instant') { _%>
        <dropDefaultValue tableName="<%= entityTableName %>" columnName="<%=fields[idx].fieldNameAsDatabaseColumn %>" columnDataType="datetime"/>
        <%_ }
        } _%>
        <% for (idx in relationships) {
            const relationshipType = relationships[idx].relationshipType,
            relationshipName = relationships[idx].relationshipName,
            ownerSide = relationships[idx].ownerSide,
            otherEntityName = relationships[idx].otherEntityName;
            if (relationshipType === 'many-to-many' && ownerSide) {
                const joinTableName = getJoinTableName(name, relationshipName, prodDatabaseType);
          _%>

        <createTable tableName="<%= joinTableName %>">
            <column name="<%= getPluralColumnName(relationshipName) %>_id" type="bigint">
                <constraints nullable="false"/>
            </column>
            <column name="<%= getPluralColumnName(name) %>_id" type="bigint">
                <constraints nullable="false"/>
            </column>
        </createTable>

        <addPrimaryKey columnNames="<%= getPluralColumnName(name) %>_id, <%= getPluralColumnName(relationshipName) %>_id" tableName="<%= joinTableName %>"/>
        <% } %><% } %>
    </changeSet>
    <!-- jhipster-needle-liquibase-add-changeset - JHipster will add changesets here, do not remove-->
</databaseChangeLog>
